//
//  CollVideoTableViewController.swift
//  SafeFoodManagerDemo
//
//  Created by 振轩 on 2018/4/17.
//  Copyright © 2018年 bob. All rights reserved.
//

import UIKit

class CollVideoTableViewController: UITableViewController {
    
    
    var dataArr:[ArticleMode]? = [ ArticleMode]()
    let header = MJRefreshNormalHeader()
   
    var deleView:DelectView? = {
        
        let frame :CGRect
        if (UIScreen.main.bounds.height == 812) {
        frame = CGRect(x: 0, y: kScreenH-64-34, width: kScreenW, height: 64+34)
        
            
        }else{
            
          frame = CGRect(x: 0, y: kScreenH-64-34, width: kScreenW, height: 64+34)
            
        }
        let deleteView = DelectView.init(frame: frame)
        
        return deleteView
        
    }()
    var   isdeleMore:Bool = false{
        
        didSet{
            
            if isdeleMore {
                self.deleView?.isHidden = false
                
                self.tableView.reloadData()
            }else{
                
                self.deleView?.isHidden = true
                self.tableView.reloadData()
            }
            
            
        }
        
        
    }
    

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpUI()
        
        //self.isdeleMore = true
        loadData()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        
         return (self.dataArr?.count) ?? 0
       
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "VideoList", for: indexPath) as! VideoTableViewCell
        
        
        //cell.isClick = self.isEdit
       
        
        cell.mode1 = self.dataArr![indexPath.row]
        cell.deleStatue = isdeleMore
        
        
        return cell
    }
    
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let mode :ArticleMode = dataArr![indexPath.row] as! ArticleMode
        
        if self.isdeleMore {
            
            mode.isSelect = !mode.isSelect
            deleView?.selectNum(calculate())
            tableView.reloadData()
            
        }else{
            let vc = LiveViewControllerViewController()
            let mode1:ReqMode = ReqMode()
            
            mode1.courseId = mode.id
            
            mode1.staffId = LoginStatuesModel.getStaffId()
            mode1.staffType = LoginStatuesModel.getUserType()
            vc.ReqM = mode1
            present(vc, animated: true, completion: nil)
            
        }
        
        
        
    }
    
    
    
    
    //加在数据。
    func loadData(){
        
        var params:[String:AnyObject] = [String:AnyObject]()
        params["type"] = 2 as AnyObject
        params["staffId"] = LoginStatuesModel.getStaffId() as AnyObject
        params["staffType"] = LoginStatuesModel.getUserType() as AnyObject
        print(params)
        
        let API:BaseReqApi = BaseReqApi.init(requestUrl: "/index.php/FoodCheckApi/courseCollectList.json", andrequestTime: 5, andParams: params as [AnyHashable : Any], andRequestMethod: YTKRequestMethod.POST, andCache: false, andCacheTime: 0, andPostToken: true)
        
        API.starRequest { (status, mess, response) in
            
            guard let dic:Dictionary = response as? [String : AnyObject] else{
                return
            }
            print(dic)
            
            
            
            if status.rawValue == 1  {
                
                let mode1  = CourseListMode.init(DIC: dic)
                self.dataArr = mode1.data as! [ArticleMode]
               
                self.tableView.reloadData()
            
            }else if (status.rawValue == 404){
                
                UIAlertView.bk_show(withTitle: mess, message: "", cancelButtonTitle: "登陆", otherButtonTitles: ["取消"], handler: { (alertView, buttonIndex) in
                    if(buttonIndex == 1){
                        
                        
                        self.gotoLogin()
                        
                    }
                })
                
                
                
                
                
            }
        }
    }
    
    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        if self.isdeleMore {
        return true
        }else{
            
            return false
        }
    }
    
    override func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        return "删除"
    }
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            
            
            
            
        }
    }
    
    
    
   
    func  upLoadDeleteCollection(){
        
        
        
        var params:[String:AnyObject] = [String:AnyObject]()
        params["type"] = 2 as AnyObject
        params["staffId"] = LoginStatuesModel.getStaffId() as AnyObject
        params["staffType"] = LoginStatuesModel.getUserType() as AnyObject
        params["courseIds"] = getDataArray() as AnyObject
        print(params)
        
        let API:BaseReqApi = BaseReqApi.init(requestUrl: "/index.php/FoodCheckApi/courseCollectDel.json", andrequestTime: 5, andParams: params as [AnyHashable : Any], andRequestMethod: YTKRequestMethod.POST, andCache: false, andCacheTime: 0, andPostToken: true)
        
        API.starRequest { (status, mess, response) in
            
            guard let dic:Dictionary = response as? [String : AnyObject] else{
                return
            }
            print(dic)
            
            
            
            if status.rawValue == 1  {
                
              
                self.loadData()
                self.isdeleMore = false
                
            }
        }
    
    
    
    
    
    }
 
    
}

extension CollVideoTableViewController{
    
    func setUpUI(){
        setDeleteView()
        setUpTableview()
        setUpNotification()
      
        
    }
    
    func setDeleteView(){
        
        //设置deleteView
        self.deleView?.block = { (type:Int) in
            
            print("--&&&")
            print(type)
            print("____^^^^")
            switch type {
            case 1:
                self.deleteAll()
                break
                
                
            case 2:
                self.cancelAll()
                break
            case 3:
                self.upLoadDeleteCollection()
                
            default:
                break
            }
            
        }
        
        
        self.tableView.addSubview(self.deleView!)
        self.deleView?.isHidden = true
        
    }
    
    func setUpTableview(){
        tableView.register(UINib(nibName: "VideoTableViewCell", bundle: nil), forCellReuseIdentifier: "VideoList")
        tableView.rowHeight = 100
        tableView.tableFooterView = UIView()
        self.deleView?.frame.origin.y = (self.deleView?.frame.origin.y)!-60
        self.deleView?.backgroundColor = UIColor.blue
        self.deleView?.isHidden = false
        header.setRefreshingTarget(self, refreshingAction: #selector(headerRefresh))
        self.tableView!.mj_header = header
    }
    
    func setUpNotification(){
        
        
        NotificationCenter.default.addObserver(self, selector: #selector(cancelEdit(notify:)), name: NSNotification.Name(rawValue: "cancel"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(gotoEdit(notify:)), name: NSNotification.Name(rawValue: "editor"), object: nil)
        
    }
    
    
    @objc func headerRefresh(){
        print("下拉刷新.")
        sleep(1)
        //重现生成数据
        loadData()
        //重现加载表格数据
        self.tableView!.reloadData()
        //结束刷新
        self.tableView!.mj_header.endRefreshing()
    }
}
extension CollVideoTableViewController{
    
    
    func calculate()->NSInteger{
        
        var  i :Int = 0
        
        for mode  in dataArr!{
            
            let mode1 : ArticleMode = mode
            
            if mode1.isSelect{
                
                i += 1
            }
        }
        return i
    }
    //删除所有
    func deleteAll(){
        
        for mode  in dataArr!{
            
            let mode1 : ArticleMode = mode
            
            
            mode1.isSelect = true
            
            
        }
        self.deleView?.selectNum((dataArr?.count)!)
        tableView.reloadData()
        
        
        
    }
    
    
    
    func cancelAll(){
        
        for mode  in dataArr!{
            
            let mode1 : ArticleMode = mode
            
            mode1.isSelect = false
            
            
        }
        
        tableView.reloadData()
        self.deleView?.selectNum(0)
        
    }
    
    //获得上传数据。
    
    func  getDataArray()->String{
        var  array = [NSInteger]()
        
        for  mode in dataArr!{
            
            let mdoe1:ArticleMode = mode
            
            
            if mdoe1.isSelect == true{
                
                array.append(mdoe1.id)
                
            }
        }
        
        let data = try? JSONSerialization.data(withJSONObject: array, options: JSONSerialization.WritingOptions.prettyPrinted)
        return NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as! String
        
    }
    ///通知处理。
    ///通知传值处理，----编辑按钮状态处理。
    @objc func gotoEdit(notify:NSNotification){
        
        let index:Int = notify.userInfo!["target"] as! Int
        
        if index == 1 {
            
            self.deleView?.isHidden = false
            isdeleMore = true
        }
    }
    @objc func cancelEdit(notify:NSNotification){
        
        let index:Int = notify.userInfo!["target"] as! Int
        
        if index == 1 {
            self.deleView?.isHidden = true
            isdeleMore = false
        }
    }
    
    
}





